package ai.zixing.mashibing.basic_class.class07;

public class Code05_PrintBinaryTree {

    public static void printTree(Node head) {
        System.out.println("Binary Tree");
        // 父节点调用第 0 层，身份是 "H"
        printInOrder(head, 0, "H", 17);
        System.out.println();
    }

    // 右头左的顺序打印
    public static void printInOrder(Node head, int heigth, String to, int len) {
        if (head == null) {
            return;
        }
        // 根据层数确定需要预留的空格
        // len ：给值定长，值如果不够17，左右补齐17个空格，更好的让值对齐
        printInOrder(head.right, heigth + 1, "v", len);
        // 给值标识身份
        String val = to + head.value + to;
        int lenM = val.length();
        int lenL = (len - lenM) / 2;
        int lenR = len - lenM - lenL;
        val = getSpace(lenL) + val + getSpace(lenR);
        System.out.println(getSpace(heigth * len) + val);
        printInOrder(head.left, heigth + 1, "^", len);
    }


    public static String getSpace(int num) {
        String space = " ";
        StringBuffer buf = new StringBuffer("");
        for (int i = 0; i < num; i++) {
            buf.append(space);
        }
        return buf.toString();
    }

    public static void main(String[] args) {
        Node head = new Node(1);
        head.left = new Node(-222222222);
        head.right = new Node(3);
        head.left.left = new Node(Integer.MIN_VALUE);
        head.right.left = new Node(55555555);
        head.right.right = new Node(66);
        head.left.left.right = new Node(777);
        printTree(head);

        head = new Node(1);
        head.left = new Node(2);
        head.right = new Node(3);
        head.left.left = new Node(4);
        head.right.left = new Node(5);
        head.right.right = new Node(6);
        head.left.left.right = new Node(7);
        printTree(head);

        head = new Node(1);
        head.left = new Node(1);
        head.right = new Node(1);
        head.left.left = new Node(1);
        head.right.left = new Node(1);
        head.right.right = new Node(1);
        head.left.left.right = new Node(1);
        printTree(head);
    }
}
